<?php
require_once __DIR__.'/../config/config_ucenter.php';
require __DIR__.'/../source/class/class_core.php';
C::app()->init();

$method = $_REQUEST['action'];
if (!method_exists('JosnData', $method)) {
    echo json_encode(array(
        'status' => 0,
        'error'  => '参数错误，方法不存在',
    ));
    exit;
}
$params = $_REQUEST;

$json = new JosnData($params);
$json->$method();


/**
 *
 */
class JosnData
{
    protected $params;
    protected $uid=0;
    protected $access_token='';
    protected $errnums = 0;
    protected $urlbase='http://dz.wonyes.org/';
    public function __construct($params = array())
    {
        $params['page']=$params['page']>0?$params['page']:1;
        $params['size']=$params['size']>0?$params['size']:10;
        $access_token=isset($_SERVER['HTTP_ACCESS_TOKEN'])?$_SERVER['HTTP_ACCESS_TOKEN']:$_REQUEST['access_token'];
        $uid=isset($_SERVER['HTTP_UID'])?$_SERVER['HTTP_UID']:$_REQUEST['uid'];
        if ($uid && $access_token) {
            $str=authcode(preg_replace('/(plusadd)/ism', '+', $access_token), 'DECODE', 'webapp', 864000);
            if (!$str) {
                $this->json(1, '登录校验出错，请重新登录');
            }
            $arr=explode(':', $str);
            if (!$arr || $arr[0]!=$uid) {
                $this->json(1, '登录出错');
            } elseif ($arr[1]+864000<time()) {
                $this->json(1, '登录过期，请重新登录');
            }
            $this->uid=$uid;
            $this->access_token=$access_token;
        }
        $this->params = $params;
    }
    
    
    
    //根据相关参数组合筛选帖子
    public function getThreadListBy()
    {
        // 获取条件
        $where=[];
        // 排序规则
        $order=[];
        // 是否按照版块选取
        if ($this->params['fid']) {
            $where[]=DB::field('fid', intval($this->params['fid']), '=');
        }
        // 是否精华
        if ($this->params['digest']>0) {
            $where[]=DB::field('digest', 0, '>');
            $order[]=DB::order('digest', 'desc');
        }
        // 是否高亮
        if ($this->params['highlight']>0) {
            $where[]=DB::field('highlight', 0, '>');
        }
        // 是否平分
        if ($this->params['rate']>0) {
            $where['rate']=DB::field('rate', 0, '>');
            $order[]=DB::order('rate ', 'desc');
        }
        
        $where[]=DB::field('closed', 0);
        
        // 开始排序规则
       
        // 回复次数
        if ($this->params['replies']) {
            $order[]=DB::order('replies', 'desc');
        }
        // 浏览次数
        if ($this->params['views']) {
            $order[]=DB::order('views', 'desc');
        }
        // 推荐指数 recommends
        if ($this->params['recommends']) {
            $order[]=DB::order('recommends', 'desc');
        }
        // 热度值 heats
        if ($this->params['heats']) {
            $order[]=DB::order('heats', 'desc');
        }
        // 收藏次数 favtimes
        if ($this->params['favtimes']) {
            $order[]=DB::order('favtimes', 'desc');
        }
        
        // 点评数 comments
        if ($this->params['comments']) {
            $order[]=DB::order('comments', 'desc');
        }
        
        
        // 最后回复时间
        if ($this->params['lastpost']) {
            $order[]=DB::order('lastpost', 'desc');
        }
        // 最后再按发布时间倒序
        $order[]=DB::order('dateline', 'desc');

        // 获取条数
        $page=(int)$this->params['page']?$this->params['page']:1;
        $size=(int)$this->params['size']?$this->params['size']:20;
        $start=($page-1)*$size;

        $data=DB::fetch_all("select * from %t WHERE ".implode(' AND ', $where).' ORDER BY '.implode(',', $order). ' LIMIT %d,%d', array('forum_thread',$start,$size), 'tid');
        
        if ($this->params['summary']>0) {
            $message=DB::fetch_all('select message,tid from %t WHERE '.DB::field('tid', array_keys($data), 'in').' and position=%d', array('forum_post',1), 'tid');
            foreach ($message as $k=>$v) {
                $data[$k]['summary']=mb_substr(preg_replace(array('/\[.*?\]/ism','/&#.*?;/ism'), array('',''), strip_tags($v['message'])), 0, 60);
                $data[$k]['cover']='http://dz.wonyes.org/1.jpg';
            }
        }
        
        $this->json(0, 'ok', array_values($data));
    }

    // 获取最新发表的帖子的快捷查询方式，实际调用 $this->getThreadListBy
    // page size fid
    public function getThreadListByNew()
    {
        $this->params=[
          "fid"=>$this->params['fid'],
          "page"=>$this->params['page'],
          "size"=>$this->params['size'],
          "dateline"=>1,
          'summary'=>$this->params['summary']?1:0
        ];
        return $this->getThreadListBy();
    }
    
    // 获取最后回复的的帖子的快捷查询方式，实际调用 $this->getThreadListBy
    // page size fid
    public function getThreadListByLastpost()
    {
        $this->params=[
          "fid"=>$this->params['fid'],
          "page"=>$this->params['page'],
          "size"=>$this->params['size'],
          "lastpost"=>1,
          'summary'=>$this->params['summary']?1:0
        ];
        return $this->getThreadListBy();
    }
    
    // 获取精华帖子的快捷查询方式，实际调用 $this->getThreadListBy
    // page size fid
    public function getThreadListByDigest()
    {
        $this->params=[
          "fid"=>$this->params['fid'],
          "page"=>$this->params['page'],
          "size"=>$this->params['size'],
          "digest"=>1,
          'summary'=>$this->params['summary']?1:0
        ];
        return $this->getThreadListBy();
    }
    
    // 首页6个元素，根据 1-6
    /**
    tabList: [{
          id: "tab01",
          name: '最新帖子',//最后回复时间 lastpost 倒序
          newsid: 1
        }, {
          id: "tab02",
          name: '最多访问',//views 倒序
          newsid: 2
        }, {
          id: "tab03",
          name: '最多回复',//replies 倒序
          newsid: 3
        }, {
          id: "tab04",
          name: '最多收藏',//favtimes倒序
          newsid: 4
        }, {
          id: "tab05",
          name: '热度',// heats 倒序
          newsid: 5
        }, {
          id: "tab06",
          name: '推荐',//recommends 倒序
          newsid: 6
        }],
    */
    public function getIndex()
    {
        $con=[
            1=>'lastpost',
            2=>'views',
            3=>'replies',
            4=>'favtimes',
            5=>'heats',
            6=>'recommends'
        ];
        $this->params=[
          "fid"=>$this->params['fid'],
          "page"=>$this->params['page'],
          "size"=>$this->params['size'],
          $con[$this->params['type']] =>1,
          'summary'=>$this->params['summary']?1:0
        ];
        
        return $this->getThreadListBy();
    }     // 发布回复内容
    public function postReply()
    {
        global $_G;
        if ($this->params['tid']<1) {
            $this->json(1, 'tid 无效');
        }
        if ($this->uid<1) {
            $this->json(1, '请重新登录');
        }
        if (mb_strlen($this->params['message'])<4) {
            $this->json(1, '回复内容至少6个字符');
        }
        
        /**
        tid,fid,subject,message
       */
        // 再插入post表
        $pid = C::t('forum_post_tableid')->insert(array('pid' => ''), true);
        $lastposition=DB::result_first('SELECT position from %t WHERE tid=%d order by position desc limit %d', array('forum_post',$this->params['tid'],1));
        if (C::t('forum_post')->insert('tid:0', array(
                'tid'       => $this->params['tid'],
                'pid'       => $pid,
                'fid'       => $this->params['fid'],
                'first'     => 0,
                'author'    => DB::result_first('SELECT username from %t WHERE uid=%d', array('common_member',$this->uid)),
                'authorid'  => $this->uid,
                'subject'   => '',
                'message'   => htmlentities($this->params['message']),
                'dateline'  => time(),
                'useip'     => $_G['clientip'],
                'port'      => $_SERVER['REMOTE_PORT'],
                'bbcodeoff' => 0,
                'smileyoff' => 0,
                'htmlon' => 1,
                'position'  => $lastposition+1,
            ), true)) {
            $this->json(0, 'ok');
        }
        $this->json(1, '发布回复出错');
    }


    
    
    // 根据tid获取帖子正文信息
    public function getBodyByTid()
    {
        global $_G;
        $imgurlbase=$this->urlbase;
        $isvip=false;
        if ($this->uid>0) {
            $vip=$this->getpay($this->uid);
            if ($vip && $vip['endtime']>time()) {
                $isvip=true;
                $imgurlbase=$this->ossurl;
            }
        }
        // 获取一楼正文帖子
        $data=C::t('forum_post')->fetch_all_by_tid_position(0, $this->params['tid'], 1);
        if ($data && $data[0]) {
            require_once libfile('function/discuzcode');
            // 处理附件及附件图片
            $hasaid=[];
            $fujian=$tupian=[];
            // 处理 [attach] [attchimg]
            $data[0]['message']=preg_replace_callback('/\[attach.*?\](\d+)\[\/attach.*?\]/ism', function ($m) use ($imgurlbase,&$hasaid,&$fujian,&$tupian) {
                $tabid=DB::result_first('select tableid from %t WHERE aid=%d', array('forum_attachment',$m[1]));
                $hasaid[]=(int)$m[1];
                if ($tabid == 0  ||  ($tabid && $tabid!=127)) {
                    $tmp=DB::fetch_first('select attachment,filename from %t WHERE aid=%d', array('forum_attachment_'.$tabid,$m[1]));
                    if (!preg_match('/(\.jpg)|(\.png)|(\.jpeg)/i', $tmp['attachment'])) {
                        $fujian[]=['url'=>$imgurlbase.'data/attachment/forum/'.$tmp['attachment'],'name'=>urlencode($tmp['filename'])];
                        return '';
                    }
                    $tupian[]=preg_match('/^https?/i', $tmp['attachment'])?$tmp['attachment']:($imgurlbase.'data/attachment/forum/'.$tmp['attachment']);
                    return '';
                }
            }, $data[0]['message']);
            
            // 处理 [img]
            preg_replace_callback('/\[img.*?\](.*?)\[\/img\]/ism', function ($m) use (&$tupian) {
                if ($m[1]) {
                    $tupian[]=preg_match('/^https?/i', $m[1])?$m[1]:($imgurlbase.$m[1]);
                }
                return '';
            }, $data[0]['message']);
            
            $data[0]['message']=discuzcode($data[0]['message'], false, false, 1, 1, 1, 1, 1, 0, 0, /*authorid*/'0', 1, /*pid*/0, 0, 0, 1);
            $data[0]['message']=htmlspecialchars_decode($data[0]['message']);
             
            // 处理 <img>
            $data[0]['message']=preg_replace_callback('/<img.*?src="(.*?(jpg|png|jpeg))"[^>]*?>/ism', function ($m) use (&$tupian) {
                if ($m[1]) {
                    $tupian[]=preg_match('/^https?/i', $m[1])?$m[1]:($imgurlbase.$m[1]);
                    return '';
                } else {
                    return '<img src="'.$m[1].'">';
                }
            }, $data[0]['message']);
           
            
            // 获取没有被包含在 message 里的附件486140
            $allaids=DB::fetch_all('select * from %t where tid=%d ORDER by  aid desc limit 50 ', array('forum_attachment',$this->params['tid']));
            $num=0;
            foreach ($allaids as $v) {
                if ($num>10) {
                    break;
                }
                if (!in_array($v['aid'], $hasaid)) {
                    $tmp=DB::fetch_first('select attachment,filename from %t WHERE aid=%d', array('forum_attachment_'.$v['tableid'],$v['aid']));
                    if (!preg_match('/(\.jpg)|(\.png)|(\.jpeg)/i', $tmp['attachment'])) {
                        $fujian[]=['url'=>$imgurlbase.'data/attachment/forum/'.$tmp['attachment'],'name'=>urlencode($tmp['filename'])];
                    } else {
                        $num++;
                        $tupian[]=preg_match('/^https?/i', $tmp['attachment'])?$tmp['attachment']:($imgurlbase.'data/attachment/forum/'.$tmp['attachment']);
                    }
                }
            }
            $data[0]['message']=strip_tags($data[0]['message']);
            $data[0]['message']=preg_replace(['/\s\d{4}\-\d{1,2}\-\d{1,2} \d{2}:\d{2}/i','/&#160;/ism'], ['',''], $data[0]['message']);
            
            $data[0]['fujian']=[];
            $data[0]['tupian']=$tupian;

            $sortid=DB::result_first('select sortid from %t WHERE tid=%d', array('forum_thread',$data[0]['tid']));
            // 处理分类信息
            if ($sortid>0) {
                $content=DB::fetch_all('select * from %t WHERE tid=%d and sortid=%d', array('forum_typeoptionvar',$data[0]['tid'],$sortid), 'optionid');
                if ($content) {
                    // 获取所有 optionid 的规则记录和类型
                    $options=DB::fetch_all('select title,optionid,rules,type from %t WHERE '.DB::field('optionid', array_keys($content), 'in'), array('forum_typeoption'), 'optionid');
                    if ($options) {
                        foreach ($options as $k=>$v) {
                            // 遍历规则类型，name即为 该项规则显示名称
                            $content[$k]['name']=$v['title'];
                            // 如果是radio checkbox select ,需要再次匹配规则中内容提取，否则不需要动
                            if (in_array($v['type'], ['radio','checkbox','select'])) {
                                // 以 \t 切割 content[$k]['value']，获取匹配规则中的某项
                                $val=explode("\t", $content[$k]['value']);
                                
                                // 将规则转为 以 设定的1=内容形式
                                $rules=explode("\n", trim(unserialize($v['rules'])['choices']));
                                $rulesarr=[];
                                array_map(function ($item) use (&$rulesarr) {
                                    $tmp=explode("=", trim($item));
                                    $rulesarr[$tmp[0]]=$tmp[1];
                                    return '';
                                }, $rules);
                                $value=$content[$k]['value'];
                                $content[$k]['value']=[];
                                // 遍历所选
                                foreach ($val as $rulekey) {
                                    $content[$k]['value'][]=$rulesarr[$rulekey];
                                }
                                $content[$k]['value']=implode(', ', $content[$k]['value']);
                            }
                        }
                        $data[0]['fenlei']=array_values($content);
                    }
                }
            }
            
            $data[0]['hasfavore']=DB::result_first('select count(favid) from %t WHERE id=%d and uid=%d and idtype=%s', array('home_favorite',$data[0]['tid'],$this->uid,'tid'));
        }
        $data[0]['forumname']=$fidjson[$data[0]['fid']]['name'];
        $this->json(0, 'ok', $data[0]);
    }
    
    // 获取回复，从2楼开始
    public function getPostByTid()
    {
        global $_G;
        $imgurlbase=$this->urlbase;
        require_once libfile('function/discuzcode');
        // 获取条数
        $page=(int)$this->params['page']?$this->params['page']:1;
        $size=(int)$this->params['size']?$this->params['size']:20;
        $start=($page-1)*$size;
        $data=DB::fetch_all('select * from %t WHERE tid=%d and '.DB::field('position', "1", '<>').' order by dateline desc limit %d,%d', array('forum_post',$this->params['tid'],$start,$size));
        $allauthorid=[];
        foreach ($data as $k=>$v) {
            $allauthorid[$v['authorid']]=$v['authorid'];
            $tupian=[];
            // // 处理附件及附件图片
            $v['message']=preg_replace_callback('/\[attach.*?\](\d+)\[\/attach.*?\]/ism', function ($m) use ($imgurlbase,&$tupian) {
                $tabid=DB::result_first('select tableid from %t WHERE aid=%d', array('forum_attachment',$m[1]));
                if ($tabid == 0  ||  ($tabid && $tabid!=127)) {
                    $tmp=DB::fetch_first('select attachment,filename from %t WHERE aid=%d', array('forum_attachment_'.$tabid,$m[1]));
                    if (preg_match('/(\.jpg)|(\.png)|(\.jpeg)/i', $tmp['attachment'])) {
                        $tupian[]=$imgurlbase.'data/attachment/forum/'.$tmp['attachment'];
                    }
                    return '';
                }
            }, $v['message']);
            
            $v['message']=preg_replace_callback('/\[img.*?\](.*?(jpg|png))\[\/img\]/ism', function ($m, &$tupian) {
                $tupian[]=$m[1];
                return  '';
            }, $v['message']);

            $v['message']=discuzcode($v['message'], false, false, 1, 1, 1, 1, 1, 0, 0, /*authorid*/'0', 1, /*pid*/0, 0, 0, 1);
            $data[$k]['message']= preg_replace([
                '/\[\w+.*?\].*?\[\/\w+.*?\]/ism',
                '/&#160;/ism'
            ], ['',''], strip_tags($v['message']));
            $data[$k]['tupian']=[];
            $avatar=avatar($v['authorid'], 'small', true);
            if (!is_file(DISCUZ_ROOT.substr($avatar, stripos($avatar, '.com')+4))) {
                $avatar=$this->urlbase.'uc_server/images/noavatar_small.gif';
            }
            $data[$k]['avatar']=$avatar;
        }


        $this->json(0, 'ok', array_values($data));
    }
    

    // 获取全部版块信息
    /**
    fid=>[
        分区信息..
        分区信息..
        forum=>[
            版块信息..
            版块信息..
            forumfield=>[
                扩展信息..
                扩展信息..
            ]
            sub=>[
                子版块信息..
                子版块信息..
                forumfield=>[
                    扩展信息..
                    扩展信息..
                ]
            ]
        ]

    ]
    */
    public function getForums()
    {
        $data=[];
        // 获取所有分区 版块 子版块
        $list=C::t('forum_forum')->fetch_all_by_status(1);
        // 记录版块对应的分区，以便正确将sub子版块插入
        $fid2fup=[];
        // 记录版块和子版块fid，获取扩展信息
        $fids=[];
        // 基url，用于图标 图片等补全
        $url=$this->urlbase;
        foreach ($list as $k=>$v) {
            // 分区
            if ($v['type']=='group') {
                $data[$v['fid']]=$v;
            } elseif ($v['type']=='forum') {
                // 直接版块
                $data[$v['fup']]['forum'][$v['fid']]=$v;
                $fid2fup[$v['fid']]=$v['fup'];
                $fids[]=$v['fid'];
            } elseif ($v['type']=='sub') {
                // 子版块
                $data[$fid2fup[$v['fup']]]['forum'][$v['fup']]['sub'][$v['fid']]=$v;
                $fids[]=$v['fid'];
            }
        }
        unset($list);
        $forumfield=C::t('forum_forumfield')->fetch_all_by_fid($fids);
        foreach ($data as $k=>$v) {
            if (!$v['forum']) {
                continue;
            }
            foreach ($v['forum'] as $k2=>$v2) {
                if ($forumfield[$k2]['icon']) {
                    $forumfield[$k2]['icon']=$url.'data/attachment/common/'.$forumfield[$k2]['icon'];
                } else {
                    $forumfield[$k2]['icon']=$url.'static/image/common/forum.gif';
                }
                $data[$k]['forum'][$k2]['forumfield']=$forumfield[$k2];
                if (!$v2['sub']) {
                    continue;
                }
                foreach ($v2['sub'] as $k3=>$v3) {
                    if ($forumfield[$k3]['icon']) {
                        $forumfield[$k3]['icon']=$url.'data/attachment/common/'.$forumfield[$k3]['icon'];
                    } else {
                        $forumfield[$k3]['icon']=$url.'static/image/common/forum.gif';
                    }
                    $data[$k]['forum'][$k2]['sub'][$k3]['forumfield']=$forumfield[$k3];
                }
            }
        }
        $data=array_values($data);
        foreach ($data as $k=>$v) {
            if ($v['forum']) {
                foreach ($v['forum'] as $k2=>$v2) {
                    if ($v2['sub']) {
                        $v['forum'][$k2]['sub']=array_values($v['forum'][$k2]['sub']);
                    }
                }
                $data[$k]['forum']=array_values($v['forum']);
            }
        }
        $this->json(0, 'ok', $data);
    }
    
    // 获取我收藏的帖子
    public function getMyFavores()
    {
        if ($this->uid<1) {
            $this->json(1, '登录无效，请重新登录');
        }
        $start=($this->params['page']-1)*$this->params['size'];
        $data=DB::fetch_all('SELECT * from %t WHERE idtype=%s and uid=%d order by dateline desc limit %d,%d', array('home_favorite','tid',$this->uid,$start,$this->params['size']));
        if (!$data) {
            $this->json(1, '还没有收藏帖子');
        }
        $this->json(0, 'ok', $data);
    }
    
    // 获取我发布的帖子
    public function getMyThread()
    {
        if ($this->uid<1) {
            $this->json(1, '登录无效，请重新登录');
        }
        $start=($this->params['page']-1)*$this->params['size'];
        $data=DB::fetch_all('SELECT * from %t WHERE authorid=%d order by dateline desc limit %d,%d', array('forum_thread',$this->uid,$start,$this->params['size']));
        if (!$data) {
            $this->json(1, '还没发布帖子');
        }
        return $this->json(0, 'ok', $data);
    }
    // 获取我参与的帖子
    public function getMyPost()
    {
        if ($this->uid<1) {
            $this->json(1, '登录无效，请重新登录');
        }
        $start=($this->params['page']-1)*$this->params['size'];
        $data=DB::fetch_all('SELECT t.subject as threadsubject,p.* from %t as t  inner join %t as p on t.tid=p.tid WHERE t.authorid!=%d and p.authorid=%d and p.first=%d order by p.dateline desc limit %d,%d', array('forum_thread','forum_post',$this->uid,$this->uid,0,$start,$this->params['size']));
        if (!$data) {
            $this->json(1, '还没参与过帖子讨论');
        }
        foreach ($data as $k=>$v) {
            $data[$k]['message']=mb_substr(strip_tags(preg_replace('/\[.*?\]/ism', '', $v['message'])), 0, 60);
        }
        return $this->json(0, 'ok', $data);
    }
    
    // 收藏帖子
    public function setFavore()
    {
        if ($this->params['tid']<1) {
            $this->json(1, '参数tid错误');
        }
        $subject=DB::result_first('SELECT subject from %t WHERE tid=%d', array('forum_thread',$this->params['tid']));
        if (!$subject) {
            $this->json(1, '帖子不存在或已被删除');
        }
        $data=[
            "uid"=>$this->uid,
            "id"=>$this->params['tid'],
            "idtype"=>"tid",
            "spaceuid"=>0,
            "title"=>$subject,
            "description"=>"",
            "dateline"=>time()
        ];
        if (DB::result_first('SELECT count(favid) from %t WHERE uid=%d and id=%d and idtype=%s', array('home_favorite',$this->uid,$this->params['tid'],'tid'))>0) {
            $this->json(0, 'ok');
        }
        if (DB::insert('home_favorite', $data)) {
            $this->json(0, 'ok');
        }
        $this->json(1, '收藏出错，请稍后重试');
    }
    
    // 取消收藏帖子
    public function removeFavore()
    {
        if ($this->params['tid']<1) {
            $this->json(1, '参数tid错误');
        }
        $subject=DB::result_first('SELECT subject from %t WHERE tid=%d', array('forum_thread',$this->params['tid']));
        if (!$subject) {
            $this->json(1, '帖子不存在或已被删除');
        }
        if (DB::result_first('SELECT count(id) from %t WHERE uid=%d and id=%d and idtype=%s', array('home_favorite',$this->uid,$this->params['tid'],'tid'))<1) {
            $this->json(0, 'ok');
        }
        if (DB::delete('home_favorite', ['uid'=>$this->uid,'id'=>$this->params['tid'],'idtype'=>'tid'])) {
            $this->json(0, 'ok');
        }
        $this->json(1, '取消收藏出错，请稍后重试');
    }
    
    public function login2reg()
    {
        $type=strtolower($this->params['type']); 
        return $this->$type();
    }
   
    // 快速注册
    public function register()
    {
        global $_G;
        $username = $this->params['username'];
        
        $password = daddslashes(($this->params['password']));
        $email    = daddslashes(($this->params['email']));
        require_once __DIR__.'/../uc_client/client.php';
        require_once __DIR__.'/../source/class/class_member.php';
        require_once __DIR__.'/../source/function/function_member.php';
        $uid = uc_user_register($username, $password, $email, '', '', $_G['clientip']);
        if ($uid && ($uid > 0)) {
            $setregip = DB::result_first('SELECT count(*) FROM %t WHERE ' . DB::field('ip', $_G['clientip']), array('common_regip'));
            if ($setregip == 1) {
                C::t('common_regip')->update_count_by_ip($_G['clientip']);
            } else {
                C::t('common_regip')->insert(array('ip' => $_G['clientip'], 'count' => 1, 'dateline' => $_G['timestamp']));
            }
            $init_arr = array('credits' => explode(',', '0,0,0,0,0,0,0,0,0'), 'profile' => array(), 'emailstatus' => 0);
            C::t('common_member')->insert($uid, $username, md5($password), $email, $_G['clientip'], 10, $init_arr);
            $data                = $this->_getuserinfo($uid);
            $data['name']        = $username;
            $data['dqlogintype'] = 'forum';
            $data['auth']        = md5(md5($uid) . 'webapp');
            $this->json(0, 'ok', $data);
        } else {
            $msg = '注册失败';
            switch ($uid) {
                case "-1":
                    $msg = '用户名不符合规则';
                    break;
                case "-2":
                    $msg = '此用户名禁止注册';
                    break;
                case "-3":
                    $msg = '已有相同用户名';
                    break;
                case "-6":
                    $msg='该邮箱已注册过';
            }
            $this->json(1, $msg.$uid, $this->params);
        }
    }
   
    // 使用论坛帐号的登录验证
    public function login()
    {
        $user      = $this->params['username'];
        $user      = addslashes($user);
        $pass      = addslashes(($this->params['password']));
        
        $info      = DB::fetch_first("SELECT * FROM " . DB::table('ucenter_members') . "  WHERE username='" . $user . "'");
        $spass     = md5(md5($pass) . $info['salt']);
        $logintype = strtolower($this->params['logintype']);
        if ($spass == $info['password']) {
            $data         = $this->_getuserinfo($info['uid']);
            // 判断是否绑定qq或者微信
            $this->json(0, 1, $data);
        } else {
            $this->json(1, '用户名或密码错误'.$pass);
        }
    }
    
    // 上传头像
    public function uploadAvatar()
    {
        if (!isset($_FILES['img'])) {
            $this->json(1, 'No uploaded avatar');
        }
        if ($_FILES['img']['error']>0) {
            $this->json(1, 'Upload error:'.$_FILES['img']['error']);
        }
        $avatar=avatar($this->uid, 'middle', true);
        if (preg_match('/^http/i', $avatar)) {
            $newavatar= DISCUZ_ROOT.substr($avatar, strpos($avatar, '/', 8)+1);
        } else {
            $newavatar=DISCUZ_ROOT.$avatar;
        }


        $path=dirname($newavatar);
        if (!is_dir($path)) {
            mkdir($path, 0777, true);
        }
        if (move_uploaded_file($_FILES['img']['tmp_name'], $newavatar)) {
            copy($newavatar, str_replace('middle', 'big', $newavatar));
            copy($newavatar, str_replace('middle', 'small', $newavatar));
            $this->json(0, 'ok', $avatar.'?'.time());
        }
        $this->json(1, 'Error uploading avatar:101', [$_FILES['img'],'new'=>$newavatar]);
    }
    

   
    
    // 更新信息     
	public function updateUserinfo()
    {
        if ($this->uid<1) {
            $this->json(1, 'Not yet logged in');
        }
        $this->json(0, 'ok', $this->_getuserinfo($this->uid));
    }

    public function getSearch()
    {
        global $_G;
        $imgurlbase=$this->urlbase;
        $keyword = $this->params['keyword'];
        $keyword = preg_replace("/(%|_)+/i", '\\\\' . "\\1", addslashes($keyword));
        
        $start   = $this->params['size'] * ($this->params['page'] - 1);
        $contind = DB::field('fid', $this->allowshow, 'in').' and '.DB::field('subject', '%' . $keyword . '%', 'like');
        $data    = DB::fetch_all("SELECT * FROM " . DB::table('forum_thread') . "  WHERE $contind order by dateline desc LIMIT " . $start . "," . $this->params['size']);
        if (!$data) {
            $this->json(1, 'No search for related posts');
        }
        $fidjson=$this->getForumsname();
        foreach ($data as $k=>$v) {
            $data[$k]['forumname']=$fidjson[$v['fid']]['name'];
            $tmp=preg_replace(array('/\[.*?\]/ism','/&#.*?;/ism','/\s\d{4}\-\d{1,2}\-\d{1,2} \d{2}:\d{2}/i'), array('','',''), strip_tags($v['message']));
            $data[$k]['summary']=mb_substr($tmp, 0, 30);
            $data[$k]['author']='';
            $fm=DB::result_first('select attachment from %t WHERE tid=%d', array('forum_threadimage',$v['tid']));
            $data[$k]['cover']=$fm?($imgurlbase.'forum/'.$fm):'';
            preg_match('/\[attach.*?\](\d+)\[/i', $v['message'], $m);
            if (!$data[$k]['cover'] && $m[1]) {
                $tabid=DB::result_first('select tableid from %t WHERE aid=%d', array('forum_attachment',$m[1]));
                if ($tabid === 0  ||  ($tabid && $tabid!=127)) {
                    $cover=DB::result_first('select attachment from %t WHERE aid=%d', array('forum_attachment_'.$tabid,$m[1]));
                    if (preg_match('/(\.jpg)|(\.png)|(\.jpeg)/i', $cover)) {
                        if (!preg_match('/^http/i', $cover)) {
                            $cover=$imgurlbase.'forum/'.$cover;
                        }
                        $data[$k]['cover']=$cover;
                    }
                }
            }
            if (!$data[$k]['cover'] &&  $allaids=DB::fetch_all('select * from %t where tid=%d and uid=%d ORDER by  aid  limit 20 ', array('forum_attachment',$v['tid'],$v['authorid']))) {
                foreach ($allaids as $av) {
                    $tmp=DB::fetch_first('select attachment,filename from %t WHERE aid=%d', array('forum_attachment_'.$av['tableid'],$av['aid']));
                    if (preg_match('/(\.jpg)|(\.png)|(\.jpeg)/i', $tmp['attachment'])) {
                        $data[$k]['cover']=preg_match('/^https?/i', $tmp['attachment'])?$tmp['attachment']:($imgurlbase.'data/attachment/forum/'.$tmp['attachment']);
                        break;
                    }
                }
            }
        }
        
        
        
        // 将搜索结果存到 common_searchindex 表，如果是pc先搜索，则正常，如果是app先搜索，
        if ($has=DB::fetch_first('select searchid,num from %t WHERE keywords = %s order by searchid desc', array('common_searchindex',$keyword))) {
            $num=(int)$has['num']+1;
            // 是否原本已存在app的搜索，之后pc又新增了，此时需要合并 num
            $apphas=DB::fetch_first('select searchid,num from %t WHERE keywords=%s and searchid != %d', array('common_searchindex',$keyword,$has['searchid']));
            if ($apphas) {
                DB::delete('common_searchindex', ['searchid'=>$apphas['searchid']]);
                $num+=(int)$apphas['num'];
            }
            
            DB::update('common_searchindex', ['num'=>$num], ['searchid'=>$has['searchid']]);
        } else {
            DB::insert('common_searchindex', [
               "srchmod"=>2,
               "keywords"=>$keyword,
               "searchstring"=>'',
               "useip"=>$_SERVER['REMOTE_ADDR'],
               "uid"=>intval($this->uid),
               "dateline"=>time(),
               "expiration"=>time()+864000,
               "threadsortid"=>0,
               "num"=>0,
               "ids"=>0
            ]);
        }
        
        $this->json(0, 'ok', $data);
    }
    private function _getuserinfo($uid)
    {
        global $_G;
        loadcache('plugin');
        $data               = array();
        $data['uid']          = $uid;
        $data['access_token']         = preg_replace('/\+/ism', 'plusadd', authcode($uid.":".time(), 'ENCODE', 'webapp', 864000));
        $data['userinfo']     = DB::fetch_first("SELECT * FROM %t WHERE uid=%d", array('common_member', $uid));
        $data['userinfo']['avatar']=avatar($uid, 'middle', true);
        return $data;
    }
    private function json($code, $msg, $data=[])
    {
        header('Content-Type: application/json; charset=utf-8');
        header('Access-Control-Allow-Origin: *');
        echo json_encode([
            "code"=>$code,
            "msg"=>$msg,
            "data"=>$data
        ]);
        exit;
    }
    private function _isutf8($str)
    {
        $len = strlen($str);
        for ($i = 0; $i < $len; $i++) {
            $c = ord($str[$i]);
            if ($c > 128) {
                if (($c > 247)) {
                    return false;
                } elseif ($c > 239) {
                    $bytes = 4;
                } elseif ($c > 223) {
                    $bytes = 3;
                } elseif ($c > 191) {
                    $bytes = 2;
                } else {
                    return false;
                }

                if (($i + $bytes) > $len) {
                    return false;
                }

                while ($bytes > 1) {
                    $i++;
                    $b = ord($str[$i]);
                    if ($b < 128 || $b > 191) {
                        return false;
                    }

                    $bytes--;
                }
            }
        }
        return true;
    }
}
